<template>
  <div class="secondhand-product-list">
    <!-- 搜索框 - 二手书风格 -->
    <van-search
      v-model="searchKey"
      placeholder="搜索二手书/作者/出版社"
      shape="round"
      background="#f5e8d0"
      @search="onSearch"
      @cancel="onCancelSearch"
	  @input="handleSearchInput"
    >
      <template #left-icon>
        <van-icon name="search" color="#8b4513" />
      </template>
    </van-search>

    <!-- 主内容区 -->
    <div class="content-wrapper">
      <!-- 分类侧边栏 -->
      <div class="category-sidebar">
        <van-sticky :offset-top="46">
          <van-sidebar v-model="activeKey" class="book-sidebar">
            <van-sidebar-item 
              v-for="(item,i) in categoryList" 
              :key="i" 
              :title="item.name" 
              @click="onClickLeftMenus(item.id)"
            />
          </van-sidebar>
        </van-sticky>
      </div>

      <!-- 商品列表 -->
      <div class="product-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list 
            v-model="loading" 
            :finished="finished" 
            finished-text="没有更多二手书了" 
            @load="loadData" 
            :immediate-check="false"
          >
            <!-- 二手书商品卡片 -->
            <div 
              v-for="(item,i) in productList" 
              :key="i" 
              class="book-card"
              @click="onDetail(item.id)"
            >
              <div class="book-image">
                <van-image
                  width="100%"
                  height="160"
                  fit="cover"
                  :src="item.pic"
                  radius="4"
                >
                  <template #default>
                    <div class="book-tags">
                      <van-tag v-if="item.discount" plain type="danger">
                        {{ item.discount }}
                      </van-tag>
                      <van-tag v-if="item.condition" plain type="warning">
                        {{ item.condition }}
                      </van-tag>
                    </div>
                  </template>
                </van-image>
              </div>

              <div class="book-info">
                <div class="title van-multi-ellipsis--l2">{{ item.title }}</div>
                <div class="author">{{ item.author || '匿名作者' }}</div>

                <div class="price-section">
                  <div class="current-price">¥{{ item.price }}</div>
                  <div class="original-price" v-if="item.originalPrice">
                    ¥{{ item.originalPrice }}
                  </div>
                </div>

                <div class="sales">
                  <van-icon name="fire-o" color="#ff976a" />
                  <span>已售{{ item.soldCount || 0 }}</span>
                </div>
              </div>
            </div>

            <!-- 无搜索结果提示 -->
            <div v-if="searchKey && productList.length === 0" class="empty-result">
              <van-icon name="search" size="40" color="#ccc" />
              <p>没有找到匹配的二手书</p>
              <van-button 
                round 
                type="primary" 
                color="#8b4513" 
                @click="onCancelSearch"
                size="small"
              >
                重新搜索
              </van-button>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
  </div>
</template>

<script>
import { showToast } from 'vant';
import { getProductListAPI } from "@/api/product.js";
import { getCategoryListAPI } from "@/api/category.js";

export default {
  data() {
    return {
      productList: [], // 从后端获取的商品列表
      categoryList: [], // 分类列表
      categoryId: 1,
      searchKey: '',
      searching: false,
      activeKey: 0,
      pageIndex: 0,
      pageSize: 8,
      totalPage: 0,
      loading: false,
      finished: false,
      refreshing: false,
      APIDomainName: '/' ,// 接口域名
			isLoading: false  // 新增：加载锁，防止重复请求
    }
  },

  created() {
    // 先获取分类列表
    getCategoryListAPI().then(result => {
      this.categoryList = result.data;
      if (this.categoryList.length > 0) {
        this.categoryId = this.categoryList[0].id;
        this.onRefresh(); // 加载默认分类商品
      }
    }).catch(() => {
      showToast('获取分类失败');
    });
  },

methods: {
    // 新增：处理输入框变化，实现实时模糊搜索
    handleSearchInput() {
      this.searching = !!this.searchKey.trim();
      this.filterProductList(); // 触发过滤
    },

    // 新增：根据搜索关键词过滤商品列表
    filterProductList() {
      if (!this.searchKey.trim()) {
        // 无搜索关键词时显示全部
        this.filteredProductList = [...this.productList];
        return;
      }

      const keyword = this.searchKey.trim().toLowerCase();
      // 模糊搜索逻辑：匹配书名、作者、出版社
      this.filteredProductList = this.productList.filter(item => {
        const titleMatch = item.title?.toLowerCase().includes(keyword) || false;
        const authorMatch = item.author?.toLowerCase().includes(keyword) || false;
        const publisherMatch = item.publisher?.toLowerCase().includes(keyword) || false;
        return titleMatch || authorMatch || publisherMatch;
      });
    },

    onSearch() {
      this.searching = true;
      this.onRefresh();
    },

    onCancelSearch() {
      this.searchKey = '';
      this.searching = false;
      this.onRefresh();
    },

    onRefresh() {
      this.pageIndex = 0;
      this.finished = false;
      this.refreshing = true;
      this.loading = true;
      this.loadData();
    },

    loadData() {
      if (this.isLoading) return;
      this.isLoading = true;
      this.pageIndex += 1;
      const params = {
        categoryId: this.searching ? undefined : this.categoryId,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        keyWord: this.searchKey.trim() || undefined
      };

      getProductListAPI(params).then(result => {
        this.totalPage = result.data.totalPage;

        if (this.refreshing) {
          this.productList = [];
          this.refreshing = false;
        }

        if (result.data.list && result.data.list.length > 0) {
          this.productList = this.productList.concat(result.data.list);
        }

        // 数据加载完成后执行过滤
        this.filterProductList();

        this.loading = false;
        if (this.pageIndex >= this.totalPage) {
          this.finished = true;
        }
      }).catch(() => {
        showToast('获取商品失败');
        this.loading = false;
        this.refreshing = false;
      }).finally(() => {
          this.isLoading = false;
        });
    },

    onClickLeftMenus(categoryId) {
      this.categoryId = categoryId;
      this.searchKey = '';
      this.searching = false;
      this.onRefresh();
    },

    onDetail(id) {
      this.$router.push({
        name: 'productDetail',
        query: { id },
      });
    }
  }
}
</script>

<style lang="less" scoped>
.secondhand-product-list {
  background-color: #f9f5ed;
  min-height: 100vh;
	padding-top: 46px;

  .van-search {
    padding: 10px;

    /deep/ .van-search__content {
      background-color: white;
    }
  }

  .content-wrapper {
    display: flex;

    .category-sidebar {
      width: 100px;
      flex-shrink: 0;

      .book-sidebar {
        width: 100%;
        background-color: #f5e8d0;

        /deep/ .van-sidebar-item {
          padding: 14px 8px;
          color: #8b4513;
          font-size: 13px;

          &--select {
            color: white;
            background-color: #8b4513;

            &::before {
              background-color: #8b4513;
            }
          }
        }
      }
    }

    .product-list {
      flex: 1;
      padding: 10px;

      .book-card {
        background-color: white;
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 10px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        display: flex;
        padding: 10px;
      }

      .book-image {
        width: 100px;
        flex-shrink: 0;
        position: relative;

        .book-tags {
          position: absolute;
          top: 5px;
          left: 5px;
          display: flex;
          gap: 5px;
        }
      }

      .book-info {
        flex: 1;
        padding-left: 10px;
        display: flex;
        flex-direction: column;

        .title {
          font-size: 14px;
          color: #333;
          margin-bottom: 5px;
        }

        .author {
          font-size: 12px;
          color: #666;
          margin-bottom: 8px;
        }

        .price-section {
          display: flex;
          align-items: center;
          margin-bottom: 5px;

          .current-price {
            color: #f44;
            font-size: 16px;
            font-weight: bold;
            margin-right: 8px;
          }

          .original-price {
            color: #999;
            font-size: 12px;
            text-decoration: line-through;
          }
        }

        .sales {
          font-size: 12px;
          color: #999;
          display: flex;
          align-items: center;
          gap: 3px;
          margin-top: auto;
        }
      }

      .empty-result {
        text-align: center;
        padding: 40px 0;
        color: #999;

        p {
          margin: 15px 0;
        }
      }
    }
  }
}
</style>